/*
 * @Author: i@douxuefeng.cn
 * @Date: 2023-01-07 12:21:20
 * @LastEditTime: 2023-01-07 15:49:14
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 * @FilePath: /iris-api/Volumes/Data/jobs/go-utils/wechat/mp/media/media.go
 */
package media

import (
	"encoding/json"
	"fmt"
	"io"

	"gitee.com/douxuefeng/go-utils/request"
	"gitee.com/douxuefeng/go-utils/wechat/mp/accesstoken"
	"gitee.com/douxuefeng/go-utils/wechat/mp/mpconfig"
	"gitee.com/douxuefeng/go-utils/wechat/mp/params"
)

type media struct {
	*mpconfig.MpConfig
}

const (
	getTempMedia        = "https://api.weixin.qq.com/cgi-bin/media/get"
	uploadPermanetMedia = "https://api.weixin.qq.com/cgi-bin/material/add_material"
)

func NewMedia(cfg *mpconfig.MpConfig) *media {
	return &media{cfg}
}

// 获取临时素材
func (m *media) GetTempMedia(mediaId string) []byte {
	token, err := accesstoken.GetAccessToken(m.MpConfig)
	if err != nil {
		fmt.Println("error getting access token:", err)
	}
	url := fmt.Sprintf(getTempMedia+"?access_token=%s&media_id=%s", token, mediaId)
	req := request.NewRequest()
	resp, _ := req.Get(url)
	var res params.MediaResponse
	json.Unmarshal(resp.Body(), &res)
	if res.ErrCode != 0 {
		var rs = make([]byte, 0)
		return rs
	}
	return resp.Body()
}

// 上传永久素材
func (m *media) UploadPermanetMedia(mediaType, filename string, reader io.Reader) params.MediaResponse {
	token, err := accesstoken.GetAccessToken(m.MpConfig)
	if err != nil {
		fmt.Println("error getting access token:", err)
	}
	url := fmt.Sprintf(uploadPermanetMedia+"?access_token=%s&type=%s", token, mediaType)
	req := request.NewRequest()
	req.SetFileReader("media", filename, reader)
	resp, _ := req.Post(url)
	var res params.MediaResponse
	json.Unmarshal(resp.Body(), &res)
	return res
}
